package common.log;

import java.util.HashMap;
import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.JsonArray;

import play.Logger;
import play.mvc.Http.Request;
import play.mvc.Scope.Session;

public class RequestLogger {
  private static final Gson JSON = new Gson();
  
  private String url = null;
  private String method = null;
  private String action = null;
  private String clientIPAddress = null;
  private String type = "html";
  private String sid = null;
  private String userID = null;
  private transient long startTime;
  private long timeSpent;
  private Map<String, Object> data = new HashMap<String, Object>();

  public RequestLogger(Request request, Session session) {
    type = Request.current().format.equals("json") ? "js" : "html";
    url = request.getBase() + request.url;
    method = request.method;
    action = request.action;
    clientIPAddress = request.headers.get("x-forwarded-for") == null ?  request.remoteAddress : request.headers.get("x-forwarded-for").value();
    sid = session.getId();
    startTime = System.currentTimeMillis();
  }
  
  public long startTimer(String timerKey) {
    Long startTime = (Long)data.get("tms." + timerKey);
    if (startTime != null) {
      Logger.warn("startTimer called but startTimer was called before for key: %s", timerKey);
      return 0;
    }
    
    long t = System.currentTimeMillis();
    data.put("tms." + timerKey, t);
    return t;
}
  
  public long stopTimer(String timerKey) {
    Long startTime = (Long)data.get("tms." + timerKey);
    long t1 = System.currentTimeMillis();
    
    if (startTime == -1) {
      Logger.warn("stopTimer called but startTimer not found for key: %s", timerKey);
      return t1;
    }
    data.put("ts." + timerKey, (t1 - startTime));
    data.remove("tms." + timerKey);
    return (t1 - startTime);
}
  
  public void finalizeRequest() {
    timeSpent = (System.currentTimeMillis() - startTime);
    String tmpS = JSON.toJson(this);
    PlainLogger.getInstance().logUserData(userID, tmpS);
  }
}
